const { ipcMain, BrowserWindow } = require('electron');
const winManager = require('../manager/winManager');
var App = null;
function listenOpenWin() {
    ipcMain.handle('user-open-win', (event, arg) => {
        const win = new BrowserWindow({
            width: arg.width || 800,
            height: arg.height || 600,
            webPreferences: {
                nodeIntegration: true
            },
            frame: false,
            transparent: arg.transparent || false,
            show: false,
        });

        win.once('ready-to-show', () => {
            win.show();
        });
        win.on('resize', (event, newBounds) => {
            win.webContents.send('sys-win-resize', {
                winid: win.uid,
                bounds: win.getBounds(),
            });
        });
        //win.webContents.openDevTools();
        const uid = winManager.createWin(win, arg.page);
        win.loadFile(`${arg.page}`);
        win.setSkipTaskbar(true);
        win.setThumbarButtons([]);
        return uid;
    });
}

function listenCloseWin() {
    ipcMain.handle('user-close-win', (event, arg) => {
        if(!arg) {
            const mainWin = winManager.getMainWin();
            if(mainWin) {
                mainWin.close();
            }
            return;
        }
        const win = winManager.getWin(arg);
        if (win) {
            winManager.closeWin(arg);
            console.log(winManager);
            win.close();

        }
    });
}

function listenResizeWin() {
    ipcMain.handle('user-resize-win', (event, args) => {
        const { uid, width, height } = args;
        let win = null;
        if (uid) {
            win = winManager.getWin(uid);
        } else {
            win = winManager.getMainWin();
        }
        const winBounds = win.getBounds();
        win.setBounds(winBounds.x, winBounds.y, width, height);
        return {
            width,
            height
        };
    });
}

function listenMoveWin() {
    ipcMain.handle('user-move-win', (event, args) => {
        const { uid, x, y } = args;
        let win = null;

        if (uid) {
            win = winManager.getWin(uid);
        } else {
            win = winManager.getMainWin();
        }
        const currentBounds = win.getBounds();

        const position = win.getPosition();
        if (position[0] !== x && position[0] !== y) {
            win.setPosition(x, y);
        }
        return {x, y};
    })
}

exports.use = function(app) {
    App = app;
    listenOpenWin();
    listenCloseWin();
    listenResizeWin();
    listenMoveWin();
}
